<?php

namespace Admin\Controller;
// use Admin\Model;
/**
 * 后台配置控制器
 * @author yangweijie <yangweijiester@gmail.com>
 */
class GoodsController extends AdminController {

	/**
   * [展示所有的商品]
   * @return [type] [description]
   * @author Weiliqiang <[<email address>]>
   */
	public function showlist()
    { 

    // 获取搜索条件，封装成$map数组
    $name             =   I('name');
    $map['a.status']  =   array('egt',0);
    if(is_numeric($name)){
        $map['a.goods_id|a.name']=   array(intval($name),array('like','%'.$name.'%'),'_multi'=>true);
        $mvp['goods_id|name']    =   array(intval($name),array('like','%'.$name.'%'),'_multi'=>true);
    }else{
        $map['a.name']    =   array('like', '%'.(string)$name.'%');
        $mvp['name']      =   array('like', '%'.(string)$name.'%');
    }

    // 计算商品列表的商品总数
    $total = D('goods')->where($mvp)->count();

    // 获取每页显示的条数
    $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;

    // 实例化分页类，传入总数和每页显示条数
    $page = new \Think\Page($total, $listRows);

    // 方法一：准备原生查询语句，进行三表查询，获取商品名、图片、价格等信息
    // $sql = "SELECT a.goods_id,a.classify_id,a.name goodsname,a.number,a.price,a.status,a.addtime,b.sale,c.path,c.name imgname from north_goods a INNER JOIN north_attr b on a.goods_id=b.goods_id INNER JOIN north_image c on a.goods_id=c.goods_id GROUP BY a.goods_id limit $page->firstRow,$page->listRows";

    // $data = D()->query($sql);

    // 方法二：用TP框架的连贯操作查询！！！
    // **注意**：第一个表，一定要用大D或大M方法实例化！！！
    $data = D('goods')->alias('a')->join('north_attr b ON a.goods_id=b.goods_id')->join('north_image c ON a.goods_id=c.goods_id')->limit($page->firstRow.','.$page->listRows)->group('a.goods_id')->field('a.goods_id,a.classify_id,a.name goodsname,a.number,a.price,a.status,a.addtime,b.sale,c.path,c.name imgname')->where($map)->order('a.goods_id desc')->select();

    // 把查询出的一些数据进行必要的解析
    $status = ['新发布' , '上架' , '下架'];
    foreach($data as &$v){
        $v['classify_id'] = M('classify')->where('id = ' . $v['classify_id'])->select()[0]['name'];
        
        $v['status'] = $status[$v['status']];
        $v['img_path'] = ltrim($v['path'],'.').$v['imgname'];
    }

    // 如果查询总数大于每页显示的条数，则显示分页
    if($total>$listRows){
        $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
    }
    $p =$page->show();
    $this->assign('_page', $p? $p: '');
	$this->assign('data' , $data);
	$this->display();
	}

	// 商品详情
	public function details()
	{
		$goods= D('goods');
		$data = $goods->refer();

		$goods = $data['goods'];
		$size = $data['size'];
		$report = $data['report'];

        // echo '<pre>';
        //     print_r($goods);
        // echo '<pre>';

		$this->assign('goods' , $goods);
		$this->assign('size' , $size);
		$this->assign('report' , $report);
		$this->display();

	}

	//
	public function add(){
		
		if (IS_GET) {
			//分类表
			$classify = new \Admin\Model\GoodsModel('classify');
			$data = $classify->addd();

			//分类
			$this->assign('Cdata' , $data[1]);
			//详情表
			$this->assign('Ddata' , $data[0]);
			$this->display();
		}

		if (IS_POST) {
			$goods = D('goods');

			
			$res = $goods->append();

			if ($res) {
				$this->success('新增成功', U('showlist'));
			}else{
				$this->error('新增失败', U('add'));
				$this->display();
			}


		}
	}
	public function index(){
		$this->display();
	}

	//修改状态
	public function up(){

		$sta = D('goods');
		$res = $sta->status();
		echo $res;

	}

	//删除尺码表
	public function del(){

		$attr = new \Admin\Model\GoodsModel('attr');
		$res = $attr->del();
		$this->ajaxReturn($res);
	}

	// 修改尺码表
	public function modify(){

		//获取修改的原值
		if (IS_GET) {
			$attr = new \Admin\Model\GoodsModel('attr');
			$info = $attr->modify();
			$this->assign('info' , $info);
			$this->display();
		}

		// 修改尺码表
		if (IS_POST) {
			$attr = new \Admin\Model\GoodsModel('attr');
			$res = $attr->modify();

			$attr_id = I('post.attr_id');

			$map['attr_id'] = ['eq' , $attr_id];
			$goods = $attr->where($map)->select();
			$goods_id = $goods[0]['goods_id'];

			if($res){
                $this->success('修改尺码成功', U("details?id=$goods_id"));
            } else {
                $this->error('没重新编辑数据 , 或非法操作');
            }
		}
	}

	/**
   * 展示商品图片
   * @return [type] [description]
   * @author Weiliqiang <[<email address>]>
   */
	public function img()
  {
    $data            = [];
    $goods_id = I('get.goods_id');

    // 获取商品图片表image中状态为非-1的图片信息
    $map['goods_id'] = $goods_id;
    $map['status']   = ['egt','0'];
    $order           = "sort desc,image_id desc";
    $data            = $this->lists('image',$map,$order);
    foreach ($data as $key => &$value) {
      $time          = time();
      $value['addtime'] = date('Y/m/d' , $time);;
    }

    // 获取当前商品id的名称和型号
    $img            = D('goods');
    $info           = $img->where("goods_id={$goods_id}")->find();
    $info           = $info['name'].$info['number'];
		$goods_name     = $data['goods_name'];

    // 渲染至前台
		$this->assign('goods_name',$info);
		$this->assign('list' , $data);
		$this->display();
	}

	/**
	 * 为单个商品添加商品图片，上传图片的方法在GoodsModel类image方法
	 * @author Weiliqiang <[<email address>]>
	 */
	public function addImg(){
		if(IS_POST){
            $image = D('image');
            $goods_id = I('post.goods_id');
            $data = [];
            $num = 0;	//计算上传图片的数量

            if($goods_id){	// 必须携带商品id才可以上传文件

                // 若检测结果有为图片，则上传图片
                if($_FILES['picture']['error'] != 4) {
                    $config = array(
                    'maxSize'    =>    3145728,    
                    'savePath'   =>    './Picture/Img/',  // 默认保存至Uploads文件夹下  
                    'saveName'   =>    array('uniqid',''),    
                    'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),    
                    'autoSub'    =>    true,    //开启子目录保存
                    'subName'    =>    array('date','Ymd'),
                    );
                    $upload = new \Think\Upload($config);// 实例化上传类
                    $info = $upload->upload();

                    // 获取保存的文件名和保存路径
                    foreach($info as $file) {
                        $data['name'] = $file['savename'];
                        $data['path'] = $file['savepath'];
                        $data['goods_id'] = $goods_id;
                        $data['status'] = '1';
                        $data['addtime'] = time();
                        $image->add($data);
                        $num++;
                    }
                }

                // 若插入数量大于0，则显示添加成功
                if($num>0){
                    //记录行为
                    action_log('update_image', 'image', $data['id'], UID);
                    $this->success('添加成功', U('Goods/img',array('goods_id'=>$goods_id)));
                } else {
                    $this->error('添加失败');
                }
            } else {
                $this->error($image->getError());
            }
        } else {
        	$goods_id = I('get.goods_id');
            $this->assign('goods_id', $goods_id);
            $this->meta_title = '新增商品图片';
	        $this->display();
        }
	}

	/**
	 * 删除商品图片
	 * @return [type] [description]
	 * @author Weiliqiang <[<email address>]>
	 */
	public function delImg(){
		$image_id = array_unique((array)I('get.image_id',0));

        if ( empty($image_id) ) {
            $this->error('请选择要操作的数据!');
        }

        $map = array('image_id' => array('in', $image_id) );

        // 注意：删除文件夹里的图片，作废，用假性删除，即将状态码改为 -1
        /*
            $info = D('image')->where($map)->select();
            echo D('image')->getLastSql();
            foreach($info as $key=>$val){
                $del_path = 'Uploads'.ltrim($val['path'].$val['name'],'.');
                unlink($del_path);
            }
        */

        $res = $this->delete('image',$map);

        if($res){
            //记录行为
            action_log('update_image', 'goods', $id, UID);
            $this->success('删除成功');
        } else {
            $this->error('删除失败！');
        }
	}

	public function price(){

		if (IS_GET) {

			$get = I('get.');
			$info['price'] = $get['price'];
			$info['goods_id'] = $get['goods_id'];
            $info['price'] =  explode(".",$info['price'])[0];
			$this->assign('info' , $info);
			$this->display();
		}

		if (IS_POST) {

			$goods_id = I('post.goods_id');
			$goods = D('goods');
			$res = $goods->price();

			if($res){
                $this->success('修改价格成功', U("details?id=$goods_id"));
            }else{
                $this->error('没重新编辑数据 , 或修改失败');
            }
		}
	}

	/**
	 * 重写adminController里的setStatus方法
	 * @param string $Model [description]
	 * @author Weiliqiang <[<email address>]>
	 */
	public function setStatus($Model=''){
		$ids    =   I('request.ids');
        $status =   I('request.status');
        $Model = I('request.model');

        if(empty($ids)){
            $this->error('请选择要操作的数据');
        }

        $map["{$Model}_id"] = array('in',$ids);
        switch ($status){
            case -1 :
                $res = $this->delete($Model, $map, array('success'=>'删除成功','error'=>'删除失败'));
                print_r($res);
                break;
            case 0  :
                $this->forbid($Model, $map, array('success'=>'禁用成功','error'=>'禁用失败'));
                break;
            case 1  :
                $res = $this->resume($Model, $map, array('success'=>'启用成功','error'=>'启用失败'));
                dump($res);
                break;
            case 2  :
                $res = $this->pulloff($Model, $map, array('success'=>'下架成功', 'error'=>'下架失败'));
                break;
            default :
                $this->error('参数错误');
                break;
        }
	}

	/**
	 * 重写adminController里的editRow方法
	 * @return [type]        [description]
	 * @author Weiliqiang <[<email address>]>
	 */
	protected function editRow ( $model ,$data, $where , $msg ){
        $id    = array_unique((array)I('ids',0));
        $id    = is_array($id) ? implode(',',$id) : $id;
        //如存在id字段，则加入该条件
        $fields = M($model)->getDbFields();
        if(in_array("{$model}_id",$fields) && !empty($id)){            
            $where = array_merge( array("{$model}_id" => array('in', $id )) ,(array)$where );
        }

        $msg   = array_merge( array( 'success'=>'操作成功！', 'error'=>'操作失败！', 'url'=>'' ,'ajax'=>IS_AJAX) , (array)$msg );
        if( M($model)->where($where)->save($data)!==false ) {
            $this->success($msg['success'],$msg['url'],$msg['ajax']);
        }else{
            $this->error($msg['error'],$msg['url'],$msg['ajax']);
        }
    }

    // 添加尺码
    public function addsize()
    {       
        $goods = D('goods');
        $goods_id = I('get.goods_id');
        $details = $goods->addsize();
        // echo '<pre>';
        //     print_r($details);
        // echo '<pre>';
        $this->assign('details' , $details);
        $this->assign('goods_id' , $goods_id);
        $this->display();
    }


    // 添加尺码action
    public function sizeaction(){

        $goods_id = I('post.goods_id');
        $data = [];
        $data['addtime'] = time();
        $data['sale'] = 0;
        $data['store'] = I('post.store');
        $data['goods_id'] = I('post.goods_id');
        $data['details_id'] = I('post.size');

        $res = M('attr')->add($data);

        if($res){
            $this->success('添加尺码成功', U("details?id=$goods_id"));
        }else{
            $this->error('添加失败');
        }
    }
}
